package com.yunxiao.cloud.web.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @description: DataSourceAsepct
 * @author: yunxiao
 * @date: 2020/1/20 9:17
 * @version: V1.0
 **/
@Aspect
@Component
@Order(1)
public class DataSourceAspect {
    private static final Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    /**
     * 加载数据源
     */
    @Pointcut("@annotation(com.yunxiao.cloud.web.config.DataSource)")
    public void pointCut(){
        // Do nothing because of AOP
    }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        Object target = joinPoint.getTarget();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        DataSourceEnum dataSourceEnum = DataSourceEnum.DEFAULT;
        try {
            Method method = target.getClass().getMethod(signature.getName(),
                    signature.getParameterTypes());
            if (method.isAnnotationPresent(DataSource.class)) {
                DataSource annotation = method.getAnnotation(DataSource.class);
                dataSourceEnum = annotation.value();
            }
        } catch (Exception e) {
            logger.error("before(JoinPoint joinPoint) error", e);
        }
        //实现aop切换数据源
        logger.info("aop切换数据源：{}" , dataSourceEnum.getName());

        DataSourceHolder.setDataSource(dataSourceEnum);
    }

    @After("pointCut()")
    public void after() {
        DataSourceHolder.clearDataSource();
    }
}
